/**
 * 函数变量信息获取接口测试用例
 *
 * Created by snowingsea on 2020/03/06.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));
const randomstring = require('randomstring');

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');
const benchmark = require('./../../../benchmark/analyse-files/logic_bombs');

module.exports = describe('/GET functions/:id/variables.json', function () {
  const administrator = new Administrator();
  let projectVersion = {};
  let testFunc;
  const newUserIds = [];
  function url(functionId) {
    return `/functions/${functionId}/variables.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => project.createRandomVersion())
      .then((res) => {
        projectVersion = res;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'get');
  common.should.be.tester(uri, url, 'get');

  // 正常请求
  it('it should get function variables', function (done) {
    projectVersion.getAllFunctions(benchmark)
      .then((allFunctions) => {
        [testFunc] = allFunctions;
        const promises = allFunctions.map((func) => {
          const { accessToken } = projectVersion.project.creator.token;
          return new Promise((resolve, reject) => { // eslint-disable-line no-unused-vars
            chai.request(uri)
              .get(url(func.functionId))
              .set('Authorization', `Bearer ${accessToken}`)
              .end((err, res) => {
                res.should.have.status(200);
                common.should.be.functionVariablesMessage(res.body);
                resolve();
              });
          });
        });
        return Promise.all(promises);
      })
      .then(() => {
        done();
      })
      .catch(done);
  });

  // 正常请求含有指针目标的数据
  it('it should get function variables with malloc', function (done) {
    const basicVariable = { variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }), typeName: 'int' };
    const arrayVariable = {
      variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }),
      elementTypeName: 'int',
      length: 5,
    };
    testFunc.addMallocVariable(basicVariable.variableName, basicVariable)
      .then(() => testFunc.addMallocVariable(arrayVariable.variableName, arrayVariable))
      .then(() => {
        chai.request(uri)
          .get(url(testFunc.functionId))
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(200);
            common.should.be.functionVariablesMessage(res.body);
            Object.keys(res.body.malloc).length.should.be.eql(2);
            res.body.malloc.should.have.property(basicVariable.variableName);
            res.body.malloc[basicVariable.variableName]['@type'].should.be.eql(basicVariable.typeName);
            if (res.body.malloc[basicVariable.variableName]['@elementType'] !== null) {
              res.body.malloc[basicVariable.variableName].should.not.have.property('@elementType');
            }
            res.body.malloc.should.have.property(arrayVariable.variableName);
            res.body.malloc[arrayVariable.variableName]['@elementType'].should.be.eql(arrayVariable.elementTypeName);
            res.body.malloc[arrayVariable.variableName]['@length'].should.be.eql(arrayVariable.length);
            done();
          });
      })
      .catch(done);
  });

  // 不可获取不存在的函数变量信息
  it('it should fail to get function variables when the function is not exists', function (done) {
    new Promise((resolve) => {
      chai.request(uri)
        .get(url('000000000000000000000000'))
        .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
        .end((err, res) => {
          res.should.have.status(404);
          common.should.be.errorMessage(res.body);
          resolve();
        });
    })
      .then(done)
      .catch(done);
  });

  // 不可获取他人项目的函数变量信息
  it('it should fail to get function variables when the project is not yours', function (done) {
    let newUser;
    administrator.createRandomTester()
      .then((newTester) => {
        newUserIds.push(newTester.userId);
        newUser = newTester;
        return newTester.getToken();
      })
      .then(() => {
        chai.request(uri)
          .get(url(testFunc.functionId))
          .set('Authorization', `Bearer ${newUser.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });
});
